package club.dataresources.util;


import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * base64工具类
 *
 * @author Tao
 */
public class Base64Util {
    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    /**
     * 使用Base64加密算法加密字符串
     *
     * @param plainText
     */
    public static String encodeStr(String plainText) {
        byte[] b = plainText.getBytes();
        Base64 base64 = new Base64();
        b = base64.encode(b);
        return new String(b);
    }

    /**
     * 使用Base64加密算法解密字符串
     *
     * @param encodeStr
     */
    public static String decodeStr(String encodeStr) {
        byte[] b = encodeStr.getBytes();
        Base64 base64 = new Base64();
        b = base64.decode(b);
        return new String(b);
    }

    /**
     * BASE64字符串解码为二进制数据
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String base64) throws Exception {
        byte[] b = base64.getBytes();
        return Base64.decodeBase64(b);
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 将文件编码为BASE64字符串
     * 大文件慎用，可能会导致内存溢出
     *
     * @param filePath 文件绝对路径
     * @return
     * @throws Exception
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }

    /**
     * BASE64字符串转回文件
     *
     * @param filePath 文件绝对路径
     * @param base64   编码字符串
     * @throws Exception
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }

    /**
     * BASE64字符串转回图片文件
     *
     * @param imgBase64 base64字符串
     * @param realPath  文件路径名
     * @return
     */
    public static Map<String, String> debase64Imgage(String imgBase64, String realPath) {
        String uuid = UUID.randomUUID().toString();
        String guuid = uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23) + uuid.substring(24);
        return debase64Imgage(imgBase64, guuid, realPath);
    }

    /**
     * BASE64字符串转回图片文件
     *
     * @param imgBase64 base64字符串
     * @param imageName 文件名
     * @param realPath  文件路径名
     * @return
     */
    public static Map<String, String> debase64Imgage(String imgBase64, String imageName, String realPath) {
        Map<String, String> map = new HashMap<>();
        //去掉base64数据头部data:image/png;base64,和尾部的' " '
        String[] ww = imgBase64.split(",");
        imgBase64 = ww[1];
        String str = ww[0];
        String[] aa = imgBase64.split("\"");
        imgBase64 = aa[0];
        //从data:image/png;base64,获取图片的类型
        int num1 = str.indexOf("/");
        int num2 = str.indexOf(";");
        String imgType = str.substring((num1 + 1), num2);
        //使用UUID为图片命名
        //拼凑成真实图片路径
        String imagePath = realPath + imageName + "." + imgType;
        map.put(imageName + "." + imgType, imagePath);
        //解码
        try {
            Base64Util.decodeToFile(imagePath, imgBase64);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 文件转换为二进制数组
     *
     * @param filePath 文件路径
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = new byte[0];
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
        }
        return data;
    }

    /**
     * 二进制数据写文件
     *
     * @param bytes    二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if(destFile==null || destFile.getParentFile()==null){
            System.out.println("==========上传图片API出现空指针异常==========");
        }
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }
}